﻿CREATE TRIGGER tr_Page_Insert
ON dbo.t_Page
FOR INSERT
AS

IF @@ROWCOUNT > 1 BEGIN
	RAISERROR('Bulk page inserts are not supported!',16,1)
	RETURN
END

DECLARE @PageNumber int,@PageID int,@ImageID int
SELECT @PageNumber = PageNumber, @PageID = ID, @ImageID = ImageID FROM inserted

IF @PageNumber < 0 -- move @PageNumber from the end
	SELECT @PageNumber = ISNULL(MAX(PageNumber),0) + 1 + @PageNumber FROM t_Page WHERE ImageID = @ImageID

UPDATE t_Page SET PageNumber = PageNumber+1
WHERE (ImageID = @ImageID AND PageNumber >= @PageNumber AND ID > @PageID) OR
			(ImageID = @ImageID AND PageNumber >= @PageNumber AND ID < @PageID)

--INSERT INTO th_Page(PageID,UserName,Action)SELECT ID,Model_Security.dbo.UserName(),'Insert' FROM inserted

